from runner import *
from inventory import *
from flask import Flask, jsonify, request
from flask_apscheduler import APScheduler
from flask_restful import reqparse, Api, Resource, abort


import logging


VALID_TOKEN = 'your_token'

app = Flask(__name__)
api = Api(app)

pwd = os.path.split(os.path.realpath(__file__))[0]
logging.basicConfig(format="%(asctime)s %(levelname)s %(funcName)s %(message)s", level=logging.INFO, filemode='a',
                    filename=pwd + '/' + 'ans.log')


parser = reqparse.RequestParser()
parser.add_argument('resources', type=list, location='json',required=False)
parser.add_argument('playbooks', type=list, location='json',required=False)
parser.add_argument('model', type=str, location='json')
parser.add_argument('args', type=str, location='json')
ansPath = '/data/ansible/'

def token_required(func):  # 装饰器函数，用于验证Token
    def wrapper(*args, **kwargs):
        token = request.headers.get('token')
        if token == VALID_TOKEN:  # Token有效，执行原来的视图函数
            return func(*args, **kwargs)
        else:
            abort(401, message='Token验证失败')
    return wrapper

class ASModeler(Resource):
    @token_required
    def post(self):
        args = parser.parse_args()
        ansible2 = Ansiable2(inventory=args.get('resources'),
                     connection='smart')  # 创建资源库对象
        ansible2.run(hosts="all", module=args.get('model'), args=args.get('args'))
        result = ansible2.get_result()
        logging.info(json.dumps(result,indent=4))
        return jsonify(result)
        
class ASPlayBooker(Resource):
    @token_required
    def post(self):
        args = parser.parse_args()
        ansible2 = Ansiable2(inventory=args.get('resources'),
                     connection='smart')  # 创建资源库对象
        hosts=[ h['ip'] for h in args.get('resources')]
        books=[f'{ansPath}{b}.yaml' for b in args.get('playbooks') ]
        for book in books:
            if not os.path.exists(book):
                return jsonify(message='%s PlayBook不存在 ' % book.replace(ansPath,''))
        ansible2.playbook(hosts=hosts,playbooks=books)
        result = ansible2.get_result()
        logging.info(json.dumps(result,indent=4))
        return jsonify(result)
    
api.add_resource(ASModeler, '/api/ansi/modeler')
api.add_resource(ASPlayBooker, '/api/ansi/playbooker')

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8093, debug=False)



